<template>
  <div class="main main-add-supply">
    <div class="part">
      <div class="p-title">
        <div class="title">新增中心药房</div>
      </div>
      <div class="p-cont">
        <el-form
          :model="form"
          :rules="editType !== 'check' ? rules : null"
          label-width="220px"
          ref="ruleFormRef"
          readonly
        >
          <div class="sub-title">
            <el-divider content-position="left">基础信息</el-divider>
          </div>
          <el-form-item prop="warehouseName">
            <template #label
              >中心药房名称
              <MyToolTip
                color="#606266"
                content="请填入该药房实体的全称便于您记录管理，不超过50个汉字。\n此项字段不会对外展示。"
            /></template>
            <el-input
              v-model="form.warehouseName"
              placeholder="请输入中心药房名称"
              :disabled="editType === 'check'"
            />
          </el-form-item>
          <el-form-item prop="businessName">
            <template #label
              >对外展示名称
              <MyToolTip
                color="#606266"
                content="请填入便于居民用户理解并符合规范要求的名字，不超过50个汉字。\n此项字段将作为药房名称展示在万户医学院App上。"
            /></template>
            <el-input
              v-model="form.businessName"
              placeholder="请输入对外展示名称"
              :disabled="editType === 'check'"
            />
          </el-form-item>
          <el-form-item prop="warehouseContact">
            <template #label
              >联系人
              <MyToolTip
                color="#606266"
                content="请填入实体药房的联系人姓名，不超过10个汉字。\n此项字段不会对外展示。"
            /></template>
            <el-input
              v-model="form.warehouseContact"
              placeholder="请输入联系人"
              :disabled="editType === 'check'"
            />
          </el-form-item>
          <el-form-item prop="warehousePhone" required>
            <template #label
              >联系电话
              <MyToolTip
                color="#606266"
                content="请填入联系人电话或手机号，不超过20个数字。\n此项字段不会对外展示。"
            /></template>
            <el-input
              v-model="form.warehousePhone"
              placeholder="请输入联系电话"
              :disabled="editType === 'check'"
            />
          </el-form-item>
          <el-form-item prop="provinceId">
            <template #label
              >联系地址
              <MyToolTip
                color="#606266"
                content="请填入实体药房的运营地址，不超过100个汉字。\n此项字段不会对外展示。"
            /></template>
            <myProCityArea
              @proCitySelectChange="proCitySelectChange"
              ref="myProCityAreaRef"
              :disabled="editType === 'check'"
            />
          </el-form-item>
          <el-form-item prop="address" required>
            <el-input
              v-model="form.address"
              placeholder="请填写详细地址"
              :disabled="editType === 'check'"
            />
          </el-form-item>
          <el-form-item prop="lonlat" required>
            <template #label
              >经纬度坐标
              <MyToolTip
                color="#606266"
                content="请填入实体药房的经纬度，用于进行物流调度服务。"
            /></template>
            <el-input
              v-model="form.lonlat"
              placeholder="经度,纬度"
              :disabled="editType === 'check'"
            />
            <div class="tip">
              <a
                target="_blank"
                href="https://api.map.baidu.com/lbsapi/getpoint/index.html"
                >点此使用百度坐标拾取工具</a
              >获取坐标数据
            </div>
          </el-form-item>
          <el-form-item prop="mySupplyArea">
            <template #label
              >供应区域
              <MyToolTip
                color="#606266"
                content="请填入该中心药房服务的区域。一个中心药房可同时服务同省、市下的多个区域，不可同时选择不同级别区域或不同省、市下的区域；同一区域下，只可绑定一个中心药房提供服务。"
            /></template>
            <el-select
              v-model="form.mySupplyArea"
              placeholder="请选择供应区域"
              clearable
              multiple
              @change="supplyAreaChange"
              ref="supplyAreaRef"
              :disabled="editType === 'check'"
            >
              <el-option
                v-for="item in supplyAreaList"
                :key="item.value"
                :label="item.label"
                :value="item.value"
                :disabled="item.disabled"
              />
            </el-select>
            <!-- <myUserRegions @userAreaChange="userAreaChange" /> -->
          </el-form-item>
          <div class="sub-title">
            <el-divider content-position="left"
              >药品追溯（药品电子监管码）<MyToolTip
                color="#606266"
                content="药品追溯是通过药品的电子监管系统，对药品的生产和流通环节进行全程监管，出现问题就可以进行责任追溯的系统，本系统当前支持阿里健康“码上放心”平台，只需填入平台追溯ID和凭条税负refld即可使用药品追溯。"
            /></el-divider>
          </div>
          <el-form-item label="">
            <template #label>药品追溯 </template>
            <el-switch
              :active-value="1"
              :inactive-value="0"
              v-model="form.reviewStatus"
              :disabled="editType === 'check'"
            />
          </el-form-item>
          <el-form-item
            label=""
            prop="toUserId"
            v-if="form.reviewStatus === 1"
            :rules="[
              { required: true, message: '追溯ID不能为空', trigger: 'blur' }
            ]"
          >
            <template #label>追溯ID </template>
            <el-input
              v-model="form.toUserId"
              placeholder="请填写追溯ID"
              :disabled="editType === 'check'"
            />
          </el-form-item>
          <el-form-item
            prop="toRefUserId"
            v-if="form.reviewStatus === 1"
            :rules="[
              { required: true, message: '追溯refld不能为空', trigger: 'blur' }
            ]"
          >
            <template #label>追溯refld </template>
            <el-input
              v-model="form.toRefUserId"
              placeholder="请填写追溯refld"
              :disabled="editType === 'check'"
            />
          </el-form-item>
          <div class="sub-title">
            <el-divider content-position="left"
              >规律用药规则<MyToolTip
                color="#606266"
                content="设置规律用药的规则，符合规则内的药品订单将被判定为规律用药。建议各参数使用以下数值：\n规律标准延后时长（天）：3\n用量向上调整限数（盒）：1\n用量向下调整限数（盒）：1\n续订通知生成前置时长（天）：3"
            /></el-divider>
          </div>
          <el-form-item prop="estimatedPickupDelayTime">
            <template #label>规律标准延后时长（天） </template>
            <el-input
              v-model.number="form.estimatedPickupDelayTime"
              placeholder="请填写数字"
              :disabled="editType === 'check'"
            />
          </el-form-item>
          <el-form-item prop="regularUpperQuantity">
            <template #label>用量向上调整限数（盒） </template>
            <el-input
              v-model.number="form.regularUpperQuantity"
              placeholder="请填写数字"
              :disabled="editType === 'check'"
            />
          </el-form-item>
          <el-form-item prop="regularDownQuantity">
            <template #label>用量向下调整限数（盒） </template>
            <el-input
              v-model.number="form.regularDownQuantity"
              placeholder="请填写数字"
              :disabled="editType === 'check'"
            />
          </el-form-item>
          <el-form-item prop="orderRenewalLeadTime">
            <template #label>续订通知生成前置时长（天） </template>
            <el-input
              v-model.number="form.orderRenewalLeadTime"
              placeholder="请填写数字"
              :disabled="editType === 'check'"
            />
          </el-form-item>
          <div class="sub-title">
            <el-divider content-position="left">物流配送</el-divider>
          </div>
          <el-form-item prop="expressKind">
            <template #label
              >配送商
              <MyToolTip
                color="#606266"
                content="平台已接入的第三方配送商包括顺丰速运和京东快递，选择第三方配送需填入月结卡号，请确认已与相关第三方配送商达成商务合作；自行配送或无法确认配送商，请选择“自营配送”"
            /></template>
            <el-radio-group
              v-model="form.expressKind"
              :disabled="editType === 'check'"
              @change="expressKindChange"
            >
              <el-radio
                v-for="(item, index) in expressList"
                :key="index"
                :label="item.value"
                >{{ item.name }}</el-radio
              >
            </el-radio-group>
          </el-form-item>
          <el-form-item
            prop="accountNo"
            v-if="form.distributors && form.distributors[0].expressKind !== 0"
            :rules="[
              {
                required: true,
                message: '月结卡号不能为空',
                trigger: 'blur'
              }
            ]"
          >
            <template #label
              >月结卡号
              <!-- <MyToolTip
                color="#606266"
                content="新增预约服务（次）\n指标定义：今日0点截止当前时间，新增的状态正常的用药管理计划单的数量。"
            /> -->
            </template>
            <el-input
              v-model.number="form.accountNo"
              placeholder="请填写数字"
              :disabled="editType === 'check'"
              @change="changeAccountNo"
            />
          </el-form-item>
          <el-form-item prop="freight" required>
            <template #label
              >每单运费（元）
              <MyToolTip
                color="#606266"
                content="每个订单收取用户的固定配送费用，仅支持正整数。"
            /></template>
            <el-input
              v-model.number="form.freight"
              placeholder="请填写数字"
              :disabled="editType === 'check'"
              @change="changeFreight"
            />
          </el-form-item>

          <el-form-item class="flex-inline">
            <template #label
              >免运费
              <MyToolTip
                color="#606266"
                content="平台支持订单满减运费功能，打开免运费功能并设置满减线后，用药订单金额大于’于满减线，则该订单的配送费自动变为0。"
            /></template>
            <el-switch
              :active-value="1"
              :inactive-value="0"
              v-model="form.freeType"
              :disabled="editType === 'check'"
            />
          </el-form-item>
          <el-form-item
            class="flex-inline"
            prop="limitFreeMoney"
            v-if="form.freeType === 1"
            :rules="[
              {
                required: true,
                message: '订单金额不能为空，且必须大于0',
                trigger: 'blur',
                pattern: /^\d+\.?\d*$/
              }
            ]"
          >
            <div class="express-num">
              <span>订单金额>=</span
              ><el-input
                v-model.number="form.limitFreeMoney"
                placeholder="请填写数字"
                :disabled="editType === 'check'"
              /><span>元时，免配送费</span>
            </div>
          </el-form-item>
          <el-form-item>
            <el-button
              type="primary"
              @click="submitForm(ruleFormRef)"
              size="large"
              :disabled="editType === 'check'"
              >提交</el-button
            >
            <el-button
              @click="resetForm(ruleFormRef)"
              size="large"
              :disabled="editType === 'check'"
              >重置</el-button
            >
          </el-form-item>
        </el-form>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { onBeforeMount, onMounted, reactive, ref, toRaw } from "vue";
import { useRoute, useRouter } from "vue-router";
import type { FormInstance } from "element-plus";
import { getWarehousesById, createAndUpdateWarehouses } from "@/api/supply";
import MyToolTip from "@/components/myToolTip.vue";
import myProCityArea from "@/components/myProCityArea.vue";
import { useUserStoreHook } from "@/store/modules/user";
import { ElMessage } from "element-plus";
const userStore = useUserStoreHook();
const userRegions = userStore.userRegions;
const route = useRoute();
const router = useRouter();
const editType = ref<"add" | "edit" | "check">("check");
const editId = ref<string | number | null>(null);
const ruleFormRef = ref<FormInstance>(null);
const myProCityAreaRef = ref();
const supplyAreaRef = ref();
const expressList = [
  {
    value: 0,
    name: "自营配送"
  },
  {
    value: 1,
    name: "第三方-顺丰速运"
  },
  {
    value: 13,
    name: "第三方-京东快递"
  }
];

const form = ref({
  warehouseName: "",
  businessName: "",
  warehouseContact: "",
  warehousePhone: "",
  provinceId: "",
  cityId: "",
  areaId: "",
  address: "",
  lonlat: "",
  longitude: "",
  latitude: "",
  mySupplyArea: [],
  supplyArea: [
    {
      type: 3,
      provinceId: "",
      provinceName: "",
      cityId: "",
      cityName: "",
      areaId: "",
      areaName: ""
    }
  ],
  reviewStatus: 0,
  toUserId: "",
  toRefUserId: "",
  estimatedPickupDelayTime: "",
  regularUpperQuantity: "",
  regularDownQuantity: "",
  orderRenewalLeadTime: "",
  expressKind: 0,
  accountNo: "",
  freight: "",
  distributors: [
    {
      expressKind: 0,
      freight: "",
      accountNo: "",
      name: ""
    }
  ],
  freeType: 0,
  limitFreeMoney: "1"
});

function changeAccountNo() {
  form.value.distributors[0].accountNo = form.value.accountNo;
}
function changeFreight() {
  form.value.distributors[0].freight = form.value.freight;
}
function supplyAreaChange(valueList) {
  supplyAreaRef.value.blur();
  // console.log("supplyAreaChange valueList:", valueList);
  if (valueList.length > 0) {
    // 基于 只能添加同地区下同级别的区域 限制，当用户选择了某项后，需要设置其上一级其他项为diseabled
    const firstV = valueList[valueList.length - 1];
    const firstProCity = firstV && firstV.split("-");
    if (firstProCity.length === 1) {
      const value = firstProCity[0];
      supplyAreaList.value.forEach(item => {
        if (item.value.includes(value)) {
          item.disabled = false;
        } else {
          item.disabled = true;
        }
      });
    } else if (firstProCity.length === 2) {
      const pro = firstProCity[0];
      const city = firstProCity[1];
      supplyAreaList.value.forEach(item => {
        if (item.value.includes(pro) && item.value.includes(city)) {
          item.disabled = false;
        } else {
          item.disabled = true;
        }
      });
    }
  } else {
    supplyAreaList.value.forEach(item => {
      item.disabled = false;
    });
  }

  // console.log("form.mySupplyArea:", form.value.mySupplyArea);
}

const rules = reactive({
  warehouseName: [
    {
      required: true,
      message: "中心药房名称不能为空,且长度不能超过50个汉字",
      trigger: "blur",
      min: 1,
      max: 50
    }
  ],
  businessName: [
    {
      required: true,
      message: "对外展示名称不能为空,且长度不能超过50个汉字",
      trigger: "blur",
      min: 1,
      max: 50
    }
  ],
  warehouseContact: [
    {
      required: true,
      message: "联系人不能为空,且长度不能超过10个汉字",
      trigger: "blur",
      min: 1,
      max: 10
    }
  ],
  warehousePhone: [
    // {
    //   required: true,
    //   message: "联系电话不能为空，且长度不超过20",
    //   trigger: "blur",
    //   min: 1,
    //   max: 20
    // },
    {
      validator: (rule: any, value: any, callback: any) => {
        if (
          /^(0|86|17951)?(13[0-9]|15[012356789]|166|17[3678]|18[0-9]|14[57])[0-9]{8}$/.test(
            value
          ) ||
          /^(0d{2,3})-?(d{7,8})$/.test(value)
        ) {
          callback();
        } else {
          callback(new Error("联系电话格式错误"));
        }
      }
    }
  ],
  // address: [
  //   { required: true, message: "省市区不能为空", trigger: "blur" },
  //   {
  //     validator: (rule: any, value: any, callback: any) => {
  //       console.log("address rule:", rule);
  //       console.log("address value:", value);
  //       callback();
  //     }
  //   }
  // ],
  provinceId: [
    {
      required: true,
      message: "省市区不能为空",
      trigger: "blur"
    }
  ],
  address: [
    {
      required: true,
      message: "联系地址不能为空,且长度不超过100",
      trigger: "blur",
      min: 1,
      max: 100
    }
  ],
  lonlat: [
    {
      validator: (rule: any, value: any, callback: any) => {
        if (!value || !value.includes(",")) {
          callback(new Error("经纬度不能为空"));
          return;
        }
        const lonLatList = value.split(",");
        const lon = lonLatList[0];
        const lat = lonLatList[1];
        if (lonLatList.length !== 2 || !lonLatList[0] || !lonLatList[1]) {
          callback(new Error("经度和纬度之间请使用逗号分割，且只有1个逗号"));
        } else if (lon < -180 || lon > 180) {
          callback(new Error("经度范围错误，经度在-180到180之间"));
        } else if (lat < -90 || lat > 90) {
          callback(new Error("纬度范围错误，纬度在-90到90之间"));
        } else {
          callback();
        }
      },
      trigger: "blur"
    }
  ],

  mySupplyArea: [
    { required: true, trigger: "blur", message: "供应区域不能为空" }
  ],

  estimatedPickupDelayTime: [
    { required: true, message: "规律标准延后时长不能为空", trigger: "blur" }
  ],
  regularUpperQuantity: [
    { required: true, message: "用量向上调整限数不能为空", trigger: "blur" }
  ],
  regularDownQuantity: [
    { required: true, message: "用量向下调整限数不能为空", trigger: "blur" }
  ],
  orderRenewalLeadTime: [
    { required: true, message: "续订通知生成前置时长不能为空", trigger: "blur" }
  ],
  expressKind: [{ required: true, message: "配送商不能为空", trigger: "blur" }],
  freight: [
    {
      validator: (rule: any, value: any, callback: any) => {
        if (!/^\d+(\.0+)?$/.test(value)) {
          callback(new Error("每单运费不能为空,且必须为正整数"));
          return;
        } else {
          callback();
        }
      },
      trigger: "blur"
    }
  ]

  // limitFreeMoney: [
  //   {
  //     validator: (rule: any, value: any, callback: any) => {
  //       if (!/^\d+\.?\d*$/.test(value)) {
  //         callback(new Error("订单金额不能为空,且必须是大于等于0的数字"));
  //         return;
  //       } else {
  //         callback();
  //       }
  //     },
  //     trigger: "blur"
  //   }
  // ]
});

function generateArea() {
  // console.log("userRegions:", userRegions);
  return userRegions.list.map(item => {
    const type = item.type;

    if (type === 2) {
      return {
        value: item.provinceId,
        label: item.provinceName,
        disabled: false
      };
    } else if (item.type === 3) {
      return {
        value: item.provinceId + "-" + item.cityId,
        label: item.provinceName + "-" + item.cityName,
        disabled: false
      };
    } else if (item.type === 4) {
      return {
        value: item.provinceId + "-" + item.cityId + "-" + item.areaId,
        label: item.provinceName + "-" + item.cityName + "-" + item.areaName,
        disabled: false
      };
    }
  });
}

function expressKindChange(value) {
  console.log("value:", value);
  form.value.distributors[0].expressKind = value;
  form.value.distributors[0].name = expressList.find(item => {
    return item.value === value;
  }).name;
  form.value.expressKind = value;
}

const supplyAreaList = ref(generateArea());

function proCitySelectChange(value) {
  form.value.provinceId = value[0];
  form.value.cityId = value[1];
  form.value.areaId = value[2];
}

function submitForm(formEl: FormInstance | undefined) {
  if (!formEl) {
    return;
  }

  formEl.validate(async valid => {
    if (valid) {
      // if (lonLatList.length !== 2) {
      //       callback(new Error("经度和纬度之间请使用逗号分割，且只有1个逗号"));
      //     } else {
      //       callback();
      //     }
      // 经纬度坐标需要特殊处理
      const lonlat = form.value.lonlat.split(/,|，/);

      form.value.longitude = lonlat[0];
      form.value.latitude = lonlat[1];

      // 供应区域需要特殊处理
      form.value.supplyArea = form.value.mySupplyArea?.map(item => {
        const valueList = item.split("-");
        const checkedValue = valueList[valueList.length - 1];
        const target = userRegions.list.find(region => {
          return (
            region.provinceId === checkedValue ||
            region.cityId === checkedValue ||
            region.areaId === checkedValue
          );
        });
        return {
          type: target.type,
          provinceId: target.provinceId,
          provinceName: target.provinceName,
          cityId: target.cityId,
          cityName: target.cityName,
          areaId: target.areaId,
          areaName: target.areaName
        };
      });
      const submitForm = Object.assign({}, form.value);
      delete submitForm.lonlat;
      delete submitForm.mySupplyArea;
      delete submitForm.expressKind;
      delete submitForm.accountNo;
      delete submitForm.freight;
      console.log("submitForm:", submitForm);
      const res = await createAndUpdateWarehouses({
        userId: userStore.userInfo.user,
        data: JSON.stringify(submitForm)
      });
      const tip = editType.value === "add" ? "新增" : "更新";
      // res为null 不是undefined，说明新增成功过了
      if (res === null) {
        ElMessage({
          message: tip + "成功",
          type: "success"
        });
        router.push({ path: "/supply/index" });
      } else {
        ElMessage({
          message: tip + "失败",
          type: "error"
        });
      }
      console.log("submit!");
    } else {
      console.log("error submit!");
      return false;
    }
  });
}
function resetForm(formEl: FormInstance | undefined) {
  if (!formEl) {
    return;
  }
  formEl.resetFields();
}

onBeforeMount(async () => {
  editId.value = route.query.id as string;
  editType.value = (route.query.type || "add") as "add" | "edit" | "check";
});
onMounted(async () => {
  if (editType.value === "edit" || editType.value === "check") {
    form.value = await getWarehousesById(editId.value);
    // defaultAreaValue.value = [
    //   form.value.provinceId,
    //   form.value.cityId,
    //   form.value.areaId
    // ];
    // 处理经纬度
    if (form.value.longitude && form.value.latitude) {
      form.value.lonlat = form.value.longitude + "," + form.value.latitude;
    } else {
      form.value.lonlat = "";
    }
    // 处理省市区
    myProCityAreaRef.value.areaValue = [
      form.value.provinceId,
      form.value.cityId,
      form.value.areaId
    ];
    // 处理供应地区
    form.value.mySupplyArea = form.value.supplyArea?.map(item => {
      let value = "";
      if (item.provinceId) {
        value = item.provinceId;
      }
      if (item.cityId) {
        value += "-" + item.cityId;
      }
      if (item.areaId) {
        value += "-" + item.areaId;
      }
      return value;
    });
    // 处理配送地址
    form.value.expressKind = form.value.distributors[0].expressKind;
    form.value.freight = form.value.distributors[0].freight;
    form.value.accountNo = form.value.distributors[0].accountNo;
  }
});
</script>
<style>
.main-add-supply .el-divider__text {
  display: flex;
  align-items: center;
  font-weight: bold;
  font-size: 16px;
  color: #333;
}

.main-add-supply .el-divider__text span {
  margin: 0px 5px;
}

.main-add-supply .el-divider__text .question-icon {
  cursor: pointer;
}
</style>
<style scoped lang="scss">
.p-cont {
  .sub-title {
    margin: 60px auto;
  }

  .el-form-item {
    width: 700px;

    ::v-deep(.el-form-item__label) {
      display: flex;
      align-items: center;
    }

    .tip {
      cursor: pointer;

      a {
        color: blue;
      }
    }

    &.flex-inline {
      ::v-deep(.el-form-item__content) {
        display: flex;
        justify-content: flex-start;
        align-items: center;

        // .express-num {
        //   margin-left: 20px;

        //   span {
        //     margin: auto 10px;
        //   }
        // }

        .el-input {
          width: 100px;
        }
      }
    }
  }
}
</style>
